package com.lw.leetcode.dp.c;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 2172. 数组的最大与和
 *
 * @author liw
 * @version 1.0
 * @date 2023/1/13 14:17
 */
public class MaximumANDSum {


    public static void main(String[] args) {
        MaximumANDSum test = new MaximumANDSum();

        // 9
//        int[] nums = {1, 2, 3, 4, 5, 6};
//        int numSlots = 3;

        // 9
        int[] nums = {15};
        int numSlots = 9;

        // 24
//        int[] nums = {1, 3, 10, 4, 7, 1};
//        int numSlots = 9;

        // 80
//        int[] nums = {1, 3, 10, 4, 7, 1, 15, 14, 13, 12, 11, 8, 6, 5, 2};
//        int numSlots = 9;

        int i = test.maximumANDSum(nums, numSlots);
        System.out.println(i);
    }


    public int maximumANDSum(int[] nums, int numSlots) {
        int l = numSlots << 1;
        int size = 1 << l;
        int length = nums.length;
        int[][] arr = new int[length][size];
        int[] items = new int[20];
        for (int i = 0; i < 20; i++) {
            items[i] = 1 << i;
        }
        for (int[] ints : arr) {
            Arrays.fill(ints, -1);
        }
        int max = 0;
        int num = nums[0];
        for (int k = 0; k < l; k++) {
            int j = items[k];
            arr[0][j] = (num & ((k >> 1) + 1));
            if (1 == length) {
                max = Math.max(max, arr[0][j]);
            }
        }

        for (int i = 1; i < length; i++) {
            num = nums[i];
            for (int j = 1; j < size; j++) {
                int c = Integer.bitCount(j);
                if (c > length) {
                    continue;
                }
                if (c == 1) {
                    arr[i][j] = Math.max(arr[i - 1][j], num & ((Integer.bitCount(j - 1) >> 1) + 1));
                    continue;
                }
                int v = arr[i - 1][j];
                for (int k = 0; k < l; k++) {
                    if ((j & items[k]) == items[k]) {
                        int t = arr[i - 1][j ^ items[k]];
                        if (t != -1) {
                            v = Math.max(v, t + (num & ((k >> 1) + 1)));
                        }
                    }
                }
                arr[i][j] = v;
                if (c == length) {
                    max = Math.max(max, arr[i][j]);
                }
            }
        }
        return max;
    }

}
